package com.parking.carsystem.parkingchargesystem.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.module.BillMessage;
import com.parking.carsystem.parkingchargesystem.module.ListDefaultOrderModule;
import com.parking.carsystem.parkingchargesystem.module.PayResult;
import com.parking.carsystem.parkingchargesystem.module.UserInfoModel;
import com.parking.carsystem.parkingchargesystem.module.WxResultmodel;
import com.parking.carsystem.parkingchargesystem.utils.Utils;
import com.parking.carsystem.parkingchargesystem.utils.WXPayUtils;
import com.parking.carsystem.parkingchargesystem.view.IosLoadingDialog;
import com.parking.carsystem.parkingchargesystem.view.ToUploadPicDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static com.parking.carsystem.parkingchargesystem.common.Constant.SDK_PAY_FLAG;

public abstract class BaseActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
    private IosLoadingDialog mLoadingDialog;
    private boolean isPermissionRequested;
    public File mPhotoFile;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            handleMessageMeathed(msg);
        }
    };

    public void handleMessageMeathed(Message msg) {
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        ButterKnife.bind(this);
        initView();
        initData();
    }

    protected abstract int getContentViewId();

    public abstract void initView();

    public abstract void initData();

    public void showToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    public void showToast(int strId) {
        Toast.makeText(this, getResources().getString(strId), Toast.LENGTH_SHORT).show();
    }

    public void showLoading() {
        if (null == mLoadingDialog) {
            IosLoadingDialog.Builder builder = new IosLoadingDialog.Builder(this)
                    .setMessage(getResources().getString(R.string.please_wait))
                    .setCancelable(false);
            builder.setShowMessage(true);
            mLoadingDialog = builder.create();
        }
        mLoadingDialog.show();
    }

    public void stopLoading() {
        if (null != mLoadingDialog && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 请求定位权限
     */
    @AfterPermissionGranted(Constant.RC_READ_LOCATION_PERM)
    public void startLocationTask() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            //登陆后开启定位权限,定位权限已经有了,不在处理
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.read_location),
                    Constant.RC_READ_LOCATION_PERM, Manifest.permission.ACCESS_FINE_LOCATION);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    /**
     * Android6.0之后需要动态申请权限
     */
    public void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionRequested) {
            isPermissionRequested = true;
            ArrayList<String> permissionsList = new ArrayList<>();
            String[] permissions = {
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.INTERNET,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CAMERA
            };

            for (String perm : permissions) {
                if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm)) {
                    permissionsList.add(perm);
                    // 进入到这里代表没有权限.
                }
            }

            if (!permissionsList.isEmpty()) {
                String[] strings = new String[permissionsList.size()];
                requestPermissions(permissionsList.toArray(strings), 0);
            }
        }
    }

    public boolean parseJson(String body) {
        try {
            JSONObject jsonObject1 = new JSONObject(body);
            int code = jsonObject1.getInt("code");
            String msg = jsonObject1.getString("msg");
            if (code == 200) {
                return true;
            } else {
                showToast(msg);
                return false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }
    public void onBack(View view){
        finish();
    }
    /**
     * 微信支付
     * @param outTradeNo
     */
    public void payWeiXin(String outTradeNo) {
        OkGo.<String>get(Constant.url + Constant.WXAPPPAY)
                .params("outTradeNo", outTradeNo)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        WxResultmodel billMessage = gson.fromJson(response.body(), WxResultmodel.class);
                        if (billMessage.code==200) {
                            JSONObject json = null;
                            //微信账单
                            try {
                                Constant.WX_APP_ID = billMessage.data.appid;
                                //994b5fd70e9432a5018e5d4e5cf5e431 微信申请appid的签名
                                String toJson = gson.toJson(billMessage.data);
                                JSONObject jsonObject = new JSONObject(toJson);
                                WXPayUtils.WXPayBuilder wxPayBuilder = new WXPayUtils.WXPayBuilder(jsonObject);
                                wxPayBuilder.build().pay(BaseActivity.this, billMessage.data.appid);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else {
                            showToast("支付失败");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });
    }
    /**
     * 阿里的支付
     * @param outTradeNo
     */
    public void payAli(String outTradeNo) {
        OkGo.<String>get(Constant.url + Constant.ALIAPPPAY)
                .params("outTradeNo", outTradeNo)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BillMessage billMessage = gson.fromJson(response.body(), BillMessage.class);
                        if (billMessage.code == 200) {
                            payMoney(billMessage.data);
                        }else {
                            showToast("支付失败");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });
    }


    public void payMoney(final String orderInfo) {
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(BaseActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
//                H5PayResultModel h5PayResultModel = alipay.h5Pay("", true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    public boolean payResponse(Message msg) {
        switch (msg.what) {
            case SDK_PAY_FLAG: {
                @SuppressWarnings("unchecked")
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                /**
                 * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    showToast("支付成功");
                    return true;
//                    finish();
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    showToast("支付失败" + payResult);
                    return false;
                }
            }
        }
        return false;
    }
    public void accountPay(String outTradeNo){
        showLoading();
        OkGo.<String>get(Constant.url+Constant.ACCOUNT_PAY)
                .params("outTradeNo",outTradeNo)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        try {
                            JSONObject jsonObject = new JSONObject( response.body());
                            int code = jsonObject.getInt("code");
                            if(code == 200 ){
                                showToast("支付成功");
                                finish();
                            }else {
                                showToast("支付失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                        showToast("支付失败");
                    }
                });
    }
    /**
     * 获取用户信息
     */
    public void getUserInfo() {
        showLoading();
        OkGo.<String>get(Constant.url + Constant.GETUSERINFO)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        Gson gson = new Gson();
                        UserInfoModel userInfoModel = gson.fromJson(response.body(), UserInfoModel.class);
                        updateData(userInfoModel);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                    }
                });
    }
    public void updateData(UserInfoModel userInfoModel){

    }

    public void showChooseIdCardUploadPicWayDialog(final int cameraReqCode, final int galleryReqCode) {
        final ToUploadPicDialog uploadADialog = new ToUploadPicDialog();
        uploadADialog.setOnClickToCameraListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadADialog.dismiss();
                openCameraTask(cameraReqCode);
//                IDCardCamera.create(ReportRepairActivity.this).openCamera(cameraReqCode);
            }
        });
        uploadADialog.setOnClickToGalleryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(galleryReqCode);
            }
        });
        uploadADialog.show(getFragmentManager(), uploadADialog.getName());
    }

    /**
     * 拍照
     */
    public void openCameraTask(int requestCode) {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            //跳入拍摄图片界面
            if (!Utils.isFastDoubleClick() && Utils.hasSDCard()) {
                //防止快速点击
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (cameraIntent.resolveActivity(this.getPackageManager()) != null) {
                    try {
                        String takePhotopath = Utils.GetSystemCaptureFullPath();
                        mPhotoFile = new File(takePhotopath);
                        Uri uri = Utils.getUriForFile(this, mPhotoFile);
                        cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        startActivityForResult(cameraIntent, requestCode);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.permission_camera),
                    Constant.RC_CAMERA_PERM, Manifest.permission.CAMERA);
        }
    }

    public void openGallery(int requestCode) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new
                    String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            //打开系统相册
            Utils.openAlbum(requestCode, this);
        }
    }
}
